#!/user/bin/env/python
#
#
# PlantPlyTools.Py
#
# B.E.Shapiro
# 5 July 2011
# (c) Caltech/Biological Network Modeling Center
# BSD Licensing Terms Apply
#

import sys
import time
import os.path
import re


def uniqueFilename(filename):
    """
    input: string filename
    returns: string filename. If file does not already exist,
        returns the same name. If file does exist, returns a unique
        file name that is similar; new names are generated as: 
        name.type --> name-1.type --> name-2.type --> name-3.type etc.
        (If there are multiple periods, the number is placed before
        the first period, starting from the left, name.sub.type -->
        name-1.sub.type --> name-2.sub.type, etc.)
    """
    f = re.sub('[\n\r]','',filename)
    exists = os.path.isfile(f)
    fn = f
    if exists:        
        i = 0
        p = f.find(".")
        if p<0:
            p = len(f)
        lhs = f[:p]
        rhs = f[p:]
        while exists:
            i += 1
            fn = lhs + "-" + str(i) + rhs
            exists = os.path.isfile(fn)
    return fn


def writePLY(filename, points, color, faces, cells=[], flags=[]):
    """
    input:  string filename
            pts: float list of 3D coordinates
            faces: integer list of faces as point indices
            cells: optional integer list of cells as face indices
            flags: optinal integer list of flags for points, e.g., 1 for centers
    action: a ply file is written to the desired file
    return: the name of the actual file written is returned
            it may be different from the requested file if the file
            previously existed
    """

    useflags = False

    if len(flags)>0:
        if len(flags)==len(points):
            useflags = True
        else:
            print "Error: writePLY: the number of flags = ", len(flags), " must equal ", \
            "the number of points = ", len(points)
            raise SystemExit("Incorrect Argument")

    fname = uniqueFilename(filename)
    f = open(fname, "w")
    f.write("ply\n")
    f.write("format ascii 1.0\n")
    f.write("element vertex " + str(len(points))+"\n")
    f.write("property float x\n")
    f.write("property float y\n")
    f.write("property float z\n")
    f.write("property uchar red\n")
    f.write("property uchar green\n")
    f.write("property uchar blue\n")
    if useflags:
        f.write("property int flag\n")
    f.write("element face " + str(len(faces))+"\n")
    f.write("property list uchar int vertex_indices\n")
    if len(cells)>0:
        f.write("element cell "+ str(len(cells))+"\n")
        f.write("property list uchar int face_indices\n")
    f.write("end_header\n")
    i = 0
    for (p,c) in zip(points,color):
        line = " ".join(map(str,p))
        line = line + " " + " ".join(map(str,c))
        if useflags:
            line = line + " " + str(flags[i])
            i += 1
        f.write( line  + "\n" )
 
    for face in faces: 
        n = len(face)
        f.write ( str(n)+" " + (" ".join(map(str,face)))+"\n" ) 

    if len(cells)> 0:
        for c in cells:
            n = len(c)
            f.write ( str(n)+" " + (" ".join(map(str,c)))+"\n" )     
  
    f.close()
    return os.path.abspath(fname)


if __name__== "__main__":
    print "PlantPyTools: " + time.ctime()
    #
    # square
    v = [ [0. ,0., 0.], [1.,0.,0.], [1.,1.,0.], [0.,1.,0.], [1., 0.,1.], [1.,1.,1.], [0.,0.,1.],\
          [0., 1., 1.], [.5, .5, .5] ]
    f = [ [0, 1, 2, 3], [1, 4, 5, 2], [0, 6, 7,3 ], [0, 1, 4, 6 ], [7, 6, 4, 5], [2, 3, 7, 5] ]
    c = [ [0, 1, 2, 3, 4, 5] ]
    # print writePLY("squares-with-flags.ply", v, f, c, flags=[0, 0, 0, 0, 0, 0,0, 0, 1] )
    # print writePLY("squares-without-flags.ply",v,f,c)
    print writePLY("squares-only.ply",v,f)
    print "Bye Bye, World!"
